package com.example.parkingsharing.ui.home

import android.os.Bundle
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import androidx.compose.runtime.Composable
import androidx.compose.ui.viewinterop.AndroidViewBinding
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.map.*
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener
import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.search.route.*
import com.example.parkingsharing.DatabaseData
import com.example.parkingsharing.DatabaseManager
import com.example.parkingsharing.MainActivity
import com.example.parkingsharing.R
import com.example.parkingsharing.databinding.MapLayoutBinding
import java.sql.Timestamp

@Composable
fun BaiduMapComposableFromLayout(
    context: MainActivity
) {
    AndroidViewBinding(MapLayoutBinding::inflate) {
        // 后台刷新车位信息
        var lastParkingList = listOf<DatabaseData>()
        Thread {
            val dbManager = DatabaseManager()
            while (true) {
                val parkingList = dbManager.get()
                bmapView.post {
                    if (parkingList == lastParkingList) {
                        return@post
                    }
                    lastParkingList = parkingList
                    bmapView.map.clear()
                    for (parking in parkingList) {
                        if (context.id == parking.booker || context.id == parking.publisher || parking.booker == "") {
                            addParkingOnMap(bmapView, parking)
                        }
                    }
                }

                Thread.sleep(300)
            }
        }.start()

        var mlocation: LatLng? = null


        // 定位
        class MyLocationListener : BDAbstractLocationListener() {
            private var firstLocation = false

            override fun onReceiveLocation(location: BDLocation) {
                // 显示定位
                val locData = MyLocationData.Builder()
                    .accuracy(location.radius) // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(location.direction).latitude(location.latitude)
                    .longitude(location.longitude).build()
                bmapView.map.setMyLocationData(locData)

                // 将地图移动到定位的位置，只定位一次
                if (!firstLocation) {
                    firstLocation = true
                    val ll = LatLng(location.latitude, location.longitude)
                    mlocation = ll
                    val builder: MapStatus.Builder = MapStatus.Builder()
                    builder.target(ll).zoom(18.0f)
                    bmapView.map.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()))
                }
            }
        }
        bmapView.map.isMyLocationEnabled = true
        val mLocationClient = LocationClient(context)
        val option = LocationClientOption()
        option.isOpenGps = true // 打开gps
        option.setCoorType("bd09ll") // 设置坐标类型
        option.setScanSpan(1000)
        mLocationClient.locOption = option
        val myLocationListener = MyLocationListener()
        mLocationClient.registerLocationListener(myLocationListener)
        mLocationClient.start()

        // 地图单击之后添加车位
        val listener: OnMapClickListener = object : OnMapClickListener {
            override fun onMapClick(point: LatLng) {
                val button = Button(context)
                button.setOnClickListener {
                    val parking = DatabaseData(
                        point.latitude, point.longitude, "", context.id,
                        Timestamp(System.currentTimeMillis())
                    )
                    // 向数据库添加车位
                    Thread {
                        val dbManager = DatabaseManager()
                        dbManager.add(parking)
                    }.start()
                }
                button.text = "添加车位"
                val tv = TextView(context)
                tv.text = "经度：${point.latitude}\n维度：${point.longitude}"
                val ll = LinearLayout(context)
                ll.orientation = LinearLayout.VERTICAL
                ll.addView(tv)
                ll.addView(button)
                val mInfoWindow = InfoWindow(ll, point, -100)
                bmapView.map.showInfoWindow(mInfoWindow)
            }

            override fun onMapPoiClick(mapPoi: MapPoi) {}
        }
        bmapView.map.setOnMapClickListener(listener)

        // 车位点击事件
        bmapView.map.setOnMarkerClickListener { marker ->
            val tv = TextView(context)
            tv.text = "经度：${marker.position.latitude}\n维度：${marker.position.longitude}"
            val navBtn = Button(context)
            navBtn.text = "导航"
            val parking = marker.extraInfo.getParcelable<DatabaseData>("parking")!!
            val btn = Button(context)
            if (context.id == parking.publisher) {
                btn.text = "删除车位"
                btn.setOnClickListener {
                    // 从数据库中删除
                    Thread {
                        val dbManager = DatabaseManager()
                        dbManager.del("${parking.latitude},${parking.longitude}")
                    }.start()
                }
            } else if (context.id == parking.booker) {
                btn.text = "取消预定"
                btn.setOnClickListener {
                    // 在数据库中取消预定
                    Thread {
                        val dbManager = DatabaseManager()
                        dbManager.update(
                            "${parking.latitude},${parking.longitude}",
                            DatabaseData(
                                parking.latitude, parking.longitude, "", parking.publisher,
                                Timestamp(System.currentTimeMillis())
                            )
                        )
                    }.start()
                }
            } else {
                btn.text = "预定车位"
                btn.setOnClickListener {
                    // 在数据库中预定车位
                    Thread {
                        val dbManager = DatabaseManager()
                        dbManager.update(
                            "${parking.latitude},${parking.longitude}",
                            DatabaseData(
                                parking.latitude, parking.longitude, context.id, parking.publisher,
                                Timestamp(System.currentTimeMillis())
                            )
                        )
                    }.start()
                }
            }
            val ll = LinearLayout(context)
            ll.orientation = LinearLayout.VERTICAL
            ll.addView(tv)
            ll.addView(navBtn)
            ll.addView(btn)
            val infoWindow = InfoWindow(ll, marker.position, -100)
            bmapView.map.showInfoWindow(infoWindow)

            navBtn.setOnClickListener {


                navigation(mlocation!!, marker.position, bmapView.map)

                lastParkingList = listOf()
                bmapView.map.clear()
                navigation(mlocation!!, marker.position, bmapView.map)

            }

            true

        }

    }
}

//驾车路线规划
fun navigation(sLocation: LatLng, eLocation: LatLng, bmapView: BaiduMap) {
    val mSearch = RoutePlanSearch.newInstance()
    val listener = object : OnGetRoutePlanResultListener {
        override fun onGetWalkingRouteResult(p0: WalkingRouteResult?) {}

        override fun onGetTransitRouteResult(p0: TransitRouteResult?) {}

        override fun onGetMassTransitRouteResult(p0: MassTransitRouteResult?) {}

        override fun onGetDrivingRouteResult(p0: DrivingRouteResult?) {
            val overlay = DrivingRouteOverlay(bmapView)
            if (p0!!.routeLines.size > 0) {
                overlay.setData(p0.routeLines.get(0))
                overlay.addToMap()
            }
        }

        override fun onGetIndoorRouteResult(p0: IndoorRouteResult?) {}

        override fun onGetBikingRouteResult(p0: BikingRouteResult?) {}

    }
    val stNode = PlanNode.withLocation(sLocation)
    val enNode = PlanNode.withLocation(eLocation)
    mSearch.setOnGetRoutePlanResultListener(listener)

    mSearch.drivingSearch(DrivingRoutePlanOption().from(stNode).to(enNode))
}

// 添加车位
fun addParkingOnMap(bmapView: MapView, parking: DatabaseData) {
    val bitmap = BitmapDescriptorFactory
        .fromResource(R.drawable.icon_mark_water)
    val bundle = Bundle()
    bundle.putParcelable("parking", parking)
    bmapView.map.addOverlay(
        MarkerOptions()
            .position(LatLng(parking.latitude, parking.longitude))
            .icon(bitmap)
            .extraInfo(bundle)
    )
}
